package com.leap.meeting.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

@Component
public class JDBCUtil {

    @Autowired
    private static DataSource ds;

    private static ThreadLocal<Connection> threadLocal =new ThreadLocal<>();

    static {
        try {
            Properties prop = new Properties();
//            InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
            InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("application.yml");
            prop.load(is);

            ds = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection(){
        try {
            //从threadLocal中获取connection
            Connection connection = threadLocal.get();
            if(connection == null){
                connection = ds.getConnection();
                connection.setAutoCommit(false);
                threadLocal.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void rollback(){
        Connection connection = threadLocal.get();
        if(connection != null){
            try {
                connection.rollback();
            } catch (SQLException e) {
                throw new RuntimeException("事务回滚失败",e);
            }
        }
    }

    public static void release(){
        try {
            Connection connection = threadLocal.get();
            if(connection != null){
                //从threadLocal中移除当前已经存储的connection对象
                threadLocal.remove();
                //如果开启了事务的手动提交,操作完毕后,归还给连接池之前,要将事务的自动提交改为true
                connection.setAutoCommit(true);
                //将connection对象归还连接池
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
